<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="bk1wz1wzS4">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css">


  <meta name="keywords" content="学习,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0">






<meta name="description" content="class类文件的结构class文件是一组以8位字节位基础单位的二进制流，采用一种类似c语言结构体的伪结构来存储数据，这种伪结构只有两种数据类型：无符号数和表。无符号数属于基本的数据类型，以u1、u2、u4、u8分别代表1个字节、2个字节、4个字节、8个字节的无符号数，无符号数可以用来描述数字、索引引用、数量值或utf-8编码构成的字符串值。表是由多个无符号数或其他表作为数据项构成的复合数据类型，">
<meta name="keywords" content="学习">
<meta property="og:type" content="article">
<meta property="og:title" content="java 字节码研究(一)">
<meta property="og:url" content="https://youandme66.github.io/2017/05/21/first/index.html">
<meta property="og:site_name" content="腊月的季节">
<meta property="og:description" content="class类文件的结构class文件是一组以8位字节位基础单位的二进制流，采用一种类似c语言结构体的伪结构来存储数据，这种伪结构只有两种数据类型：无符号数和表。无符号数属于基本的数据类型，以u1、u2、u4、u8分别代表1个字节、2个字节、4个字节、8个字节的无符号数，无符号数可以用来描述数字、索引引用、数量值或utf-8编码构成的字符串值。表是由多个无符号数或其他表作为数据项构成的复合数据类型，">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step1.png">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step2.png">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step3.png">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step4.jpg">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step5.jpg">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step6.png">
<meta property="og:image" content="https://youandme66.github.io/2017/05/21/first/step7.png">
<meta property="og:updated_time" content="2017-05-21T08:34:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java 字节码研究(一)">
<meta name="twitter:description" content="class类文件的结构class文件是一组以8位字节位基础单位的二进制流，采用一种类似c语言结构体的伪结构来存储数据，这种伪结构只有两种数据类型：无符号数和表。无符号数属于基本的数据类型，以u1、u2、u4、u8分别代表1个字节、2个字节、4个字节、8个字节的无符号数，无符号数可以用来描述数字、索引引用、数量值或utf-8编码构成的字符串值。表是由多个无符号数或其他表作为数据项构成的复合数据类型，">
<meta name="twitter:image" content="https://youandme66.github.io/2017/05/21/first/step1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'youandme'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://youandme66.github.io/2017/05/21/first/">





  <title> java 字节码研究(一) | 腊月的季节 </title>
  <script>
  (function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">腊月的季节</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope="" itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://youandme66.github.io/2017/05/21/first/">

  <span style="display:none" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <meta itemprop="name" content="腊月的季节">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="腊月的季节">
    <span style="display:none" itemprop="logo" itemscope="" itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="腊月的季节" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                java 字节码研究(一)
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-05-21T00:00:00+08:00">
                2017-05-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
            <!--noindex-->
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                  <a href="/2017/05/21/first/#comments" itemprop="discussionUrl">
                    <span class="post-comments-count hc-comment-count" data-xid="2017/05/21/first/" itemprop="commentsCount"></span>
                  </a>
                </span>
              </span>
              <!--/noindex-->
            
          

          

          
          
             <span id="/2017/05/21/first/" class="leancloud_visitors" data-flag-title="java 字节码研究(一)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="class类文件的结构"><a href="#class类文件的结构" class="headerlink" title="class类文件的结构"></a>class类文件的结构</h3><p>class文件是一组以8位字节位基础单位的二进制流，采用一种类似c语言结构体的伪结构来存储数据，这种伪结构只有两种数据类型：无符号数和表。无符号数属于基本的数据类型，以u1、u2、u4、u8分别代表1个字节、2个字节、4个字节、8个字节的无符号数，无符号数可以用来描述数字、索引引用、数量值或utf-8编码构成的字符串值。表是由多个无符号数或其他表作为数据项构成的复合数据类型，所有表都习惯性地以_info结尾。</p>
<h3 id="结构体"><a href="#结构体" class="headerlink" title="结构体"></a>结构体</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">sFile &#123;</span><br><span class="line">    u4 magic;                   //魔数</span><br><span class="line">    u2 minor_version;           //副版本号    </span><br><span class="line">    u2 major_version;           //主版本号</span><br><span class="line">    u2 constant_pool_count;     //常量池计数器，</span><br><span class="line">    cp_info constant_pool[constant_pool_count-1]; //常量池列表    </span><br><span class="line">    u2 access_flags;            //访问标志    </span><br><span class="line">    u2 this_class;              //类索引，表示这个Class文件所定义的类或接口    </span><br><span class="line">    u2 super_class;             //父类索引</span><br><span class="line">    u2 interfaces_count;        //接口计数器    </span><br><span class="line">    u2 interfaces[interfaces_count];    //接口表，接口顺序和源代码顺序一致    </span><br><span class="line">    u2 fields_count;                    //字段计数器    </span><br><span class="line">    field_info fields[fields_count];    //字段表    </span><br><span class="line">    u2 methods_count;                   //方法计数器    </span><br><span class="line">    method_info methods[methods_count]; //方法表</span><br><span class="line">    u2 attributes_count;                //属性计数器    </span><br><span class="line">    attribute_info attributes[attributes_count];    //属性表</span><br></pre></td></tr></table></figure>
<p>图示<br><img src="/2017/05/21/first/step1.png" alt="加载中"></p>
<h3 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h3><p>建立一个类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.test.doc.exp;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestClassCode</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String    attribute_1;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> Integer attribute_2;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInterface_1</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">testInterface_2</span><span class="params">(String param)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> param;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>TestClassCode.class对应的字节码如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">cafe babe 0000 0032 0018 0700 0201 001e 636f 6d2f 7465 7374 2f64 6f63 2f65 7870</span><br><span class="line">2f54 6573 7443 6c61 7373 436f 6465 0700 0401 0010 6a61 7661 2f6c 616e 672f 4f62</span><br><span class="line">6a65 6374 0100 0b61 7474 7269 6275 7465 5f31 0100 124c 6a61 7661 2f6c 616e 672f</span><br><span class="line">5374 7269 6e67 3b01 000b 6174 7472 6962 7574 655f 3201 0013 4c6a 6176 612f 6c61</span><br><span class="line">6e67 2f49 6e74 6567 6572 3b01 0006 3c69 6e69 743e 0100 0328 2956 0100 0443 6f64</span><br><span class="line">650a 0003 000d 0c00 0900 0a01 000f 4c69 6e65 4e75 6d62 6572 5461 626c 6501 0012</span><br><span class="line">4c6f 6361 6c56 6172 6961 626c 6554 6162 6c65 0100 0474 6869 7301 0020 4c63 6f6d</span><br><span class="line">2f74 6573 742f 646f 632f 6578 702f 5465 7374 436c 6173 7343 6f64 653b 0100 0f74</span><br><span class="line">6573 7449 6e74 6572 6661 6365 5f31 0100 0f74 6573 7449 6e74 6572 6661 6365 5f32</span><br><span class="line">0100 2628 4c6a 6176 612f 6c61 6e67 2f53 7472 696e 673b 294c 6a61 7661 2f6c 616e</span><br><span class="line">672f 5374 7269 6e67 3b01 0005 7061 7261 6d01 000a 536f 7572 6365 4669 6c65 0100</span><br><span class="line">1254 6573 7443 6c61 7373 436f 6465 2e6a 6176 6100 2100 0100 0300 0000 0200 0200</span><br><span class="line">0500 0600 0000 0400 0700 0800 0000 0300 0100 0900 0a00 0100 0b00 0000 2f00 0100</span><br><span class="line">0100 0000 052a b700 0cb1 0000 0002 000e 0000 0006 0001 0000 0003 000f 0000 000c</span><br><span class="line">0001 0000 0005 0010 0011 0000 0001 0012 000a 0001 000b 0000 002b 0000 0001 0000</span><br><span class="line">0001 b100 0000 0200 0e00 0000 0600 0100 0000 0b00 0f00 0000 0c00 0100 0000 0100</span><br><span class="line">1000 1100 0000 0100 1300 1400 0100 0b00 0000 3600 0100 0200 0000 022b b000 0000</span><br><span class="line">0200 0e00 0000 0600 0100 0000 0e00 0f00 0000 1600 0200 0000 0200 1000 1100 0000</span><br><span class="line">0000 0200 1500 0600 0100 0100 1600 0000 0200 17</span><br></pre></td></tr></table></figure></p>
<p>结构分析<br>魔数<br>class文件对应的字节码：cafe babe，每个class文件的头4个字节称为魔数（cafe babe），它的唯一作用是确定这个文件是否为一个能被虚拟机接受的class文件。<br>版本号<br>class文件对应的字节码：0000 0032，第5、6个字节是次版本号（minor_version），第7、8个字节是主版本号（major_version）。java的版本号是从45开始的，jdk1.1之后的每个jdk大版本发布主版本号向上＋1，高版本的jdk能向下兼容以前版本的class文件，但不能运行以后版本的class文件，即使文件格式发生任何变化，虚拟机也拒绝执行超过其版本号的class文件。<br>本例中次版本号：0x0000，主版本号：0x0032，代表编译器使用jdk1.6.0_1版本。<br>常量池计数器、数据区<br>常量池是class文件中非常重要的结构，它描述着整个class文件的字面量信息，可以理解为class文件之中的资源仓库。常量池是由一组 constant_pool 结构体数组组成的，而数组的大小则由常量池计数器指定。常量池计数器 constant_pool_count 的值 =constant_pool表中的成员数 + 1。constant_pool表的索引值只有在大于 0 且小于 constant_pool_count时才会被认为是有效的。<br>本例中常量池容量为0x0018，代表十进制数24，常量池中有23项常量，所以范围为1-23。在class文件格式规范制定之时，设计者将第0项常量空出来是有特殊考虑的，这样做的目的在于满足后面某些常量池的索引值的数据在特定情况下需要表达“不引用任何一个常量池项目”的含义，这种情况可以把索引值置为0来表示。<strong> class文件结构中只有常量池的容量计数是从1开始 </strong>。<br>接下来存储的是常量池数据区，主要存放两大类常量：字面量和符号引用，常量池中每一个常量都是一个表，共有14中不同结构的表结构数据：</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>标志</th>
</tr>
</thead>
<tbody>
<tr>
<td>CONSTANT_Utf8_info</td>
<td>1</td>
</tr>
<tr>
<td>CONSTANT_Integer_info</td>
<td>3</td>
</tr>
<tr>
<td>CONSTANT_Float_info</td>
<td>4</td>
</tr>
<tr>
<td>CONSTANT_Long_info</td>
<td>5</td>
</tr>
<tr>
<td>CONSTANT_Double_info</td>
<td>6</td>
</tr>
<tr>
<td>CONSTANT_Class_info</td>
<td>7</td>
</tr>
<tr>
<td>CONSTANT_String_info</td>
<td>8</td>
</tr>
<tr>
<td>CONSTANT_Fielddef_info</td>
<td>9</td>
</tr>
<tr>
<td>CONSTANT_Methoddef_info</td>
<td>10</td>
</tr>
<tr>
<td>CONSTANT_InterfaceMethoddef_info</td>
<td>11</td>
</tr>
<tr>
<td>CONSTANT_NameAndType_info</td>
<td>12</td>
</tr>
<tr>
<td>CONSTANT_MethodHandle_info</td>
<td>15</td>
</tr>
<tr>
<td>CONSTANT_MethodType_info</td>
<td>16</td>
</tr>
<tr>
<td>CONSTANT_InvokeDynamic_info</td>
<td>18</td>
</tr>
</tbody>
</table>
<p>之所以说常量池是最繁琐的数据，是因为常见的11个常量各自均有自己的结构，见下图：<br><img src="/2017/05/21/first/step2.png" alt="加载中"><br>以TestClassCode.java为例，格式化展示对应的常量区字节码：<br><img src="/2017/05/21/first/step3.png" alt="加载中"><br>第一项常量值：0x07 0002，它的标志位是0x07，属于CONSTANT_Class_info，此类型代表一个类或接口的符号引用。0x0002，是它的符号引用，指向常量池的第二项常量。<br>第二项常量值：0x01 001e 636f 6d2f 7465 7374 2f64 6f63 2f65 7870 2f54 6573 7443 6c61 7373 436f 6465 ，它的标志位是0x01，属于CONSTANT_Utf8_info，此类型代表一个UTF-8编码的字符串，长度为001e即十进制数30，字符串值为0x636f 6d2f 7465 7374 2f64 6f63 2f65 7870 2f54 6573 7443 6c61 7373 436f 6465，对应为：com/test/doc/exp/TestClassCode。<br>以此方法，我们可以依次得到剩下的常量池数据区，当然也可以使用javap -verbose TestClassCode命令，输出TestClassCode.class对应的常量池区域：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">Constant pool:</span><br><span class="line">   <span class="comment">#1 = Class              #2             //  com/test/doc/exp/TestClassCode</span></span><br><span class="line">   <span class="comment">#2 = Utf8               com/test/doc/exp/TestClassCode</span></span><br><span class="line">   <span class="comment">#3 = Class              #4             //  java/lang/Object</span></span><br><span class="line">   <span class="comment">#4 = Utf8               java/lang/Object</span></span><br><span class="line">   <span class="comment">#5 = Utf8               attribute_1</span></span><br><span class="line">   <span class="comment">#6 = Utf8               Ljava/lang/String;</span></span><br><span class="line">   <span class="comment">#7 = Utf8               attribute_2</span></span><br><span class="line">   <span class="comment">#8 = Utf8               Ljava/lang/Integer;</span></span><br><span class="line">   <span class="comment">#9 = Utf8               &lt;init&gt;</span></span><br><span class="line">  <span class="comment">#10 = Utf8               ()V</span></span><br><span class="line">  <span class="comment">#11 = Utf8               Code</span></span><br><span class="line">  <span class="comment">#12 = Methodref               #3.#13         //  java/lang/Object."&lt;init&gt;":()V</span></span><br><span class="line">  <span class="comment">#13 = NameAndType        #9:#10         //  "&lt;init&gt;":()V</span></span><br><span class="line">  <span class="comment">#14 = Utf8               LineNumberTable</span></span><br><span class="line">  <span class="comment">#15 = Utf8               LocalVariableTable</span></span><br><span class="line">  <span class="comment">#16 = Utf8               this</span></span><br><span class="line">  <span class="comment">#17 = Utf8               Lcom/test/doc/exp/TestClassCode;</span></span><br><span class="line">  <span class="comment">#18 = Utf8               testInterface_1</span></span><br><span class="line">  <span class="comment">#19 = Utf8               testInterface_2</span></span><br><span class="line">  <span class="comment">#20 = Utf8               (Ljava/lang/String;)Ljava/lang/String;</span></span><br><span class="line">  <span class="comment">#21 = Utf8               param</span></span><br><span class="line">  <span class="comment">#22 = Utf8               SourceFile</span></span><br><span class="line">  <span class="comment">#23 = Utf8               TestClassCode.java</span></span><br></pre></td></tr></table></figure></p>
<p>访问标志<br>常量池结束之后，紧接着的两个字节代表访问标志（access_flags），这个标志用于识别一些类或接口层次的访问信息。具体的标志位以及标志含义见下表：<br><img src="/2017/05/21/first/step4.jpg" alt="加载中"><br>本例中访问标志为0x0021，它的ACC_PUBLIC，ACC_SUPER标志应当为真，而其他标志为假。</p>
<p>类索引、父类索引、接口索引集合<br>类索引和父类索引都是一个u2类型的数据，而结构索引集合是一组u2类型的数据集合，class文件由这三项数据来确定这个类的父类的全限定名。对于接口索引集合的第一项是接口计数器，如果没有实现任何接口，该计数器为0。<br>本例中，类索引对应0x0001，即类索引指向常量池第一个变量，常量池对应为CONSTANT_Class_info的类描述符常量，再通过该变量的索引值找到定义在CONSTANT_Utf8_info类型中的全限定名字符串com/test/doc/exp/TestClassCode。父类索引为0x0003，值为java/lang/Object。接口索引集合为0x0000，即当前不实现任何接口。</p>
<p>字段表集合<br>字段表集合用于描述接口或类中声明的变量，是指由若干个字段表（field_info）组成的集合。对于在类中定义的若干个字段，经过JVM编译成class文件后，会将相应的字段信息组织到一个叫做字段表集合的结构中，字段表集合是一个类数组结构，会将类中定义的字段个数设到字段计数器中，然后每个字段信息组成一个field_info结构，依次存储到字段计数器之后。<br>field_info结构如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">struct field_info &#123;</span><br><span class="line">u2 access_flags;</span><br><span class="line">u2 name_index;</span><br><span class="line">u2 descriptor_index;</span><br><span class="line">u2 attributes_count;</span><br><span class="line">attribute_info attributes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>access_flags是一个u2的数据类型，字段访问标志包括：ACC_PUBLIC、ACC_PRIVATE、ACC_PROTECTED、ACC_STATIC、ACC_FINAL、ACC_VOLATILE、ACC_TRANSIENT、ACC_SYNTHETIC、ACC_ENUM。<br><img src="/2017/05/21/first/step5.jpg" alt="加载中"><br>跟随access_flags标志的是两个索引值：name_index和descriptor_index。他们都是对常量池的引用，分别代表字段的简单名称以及字段和方法的描述符。本例中字段表集合值对应0x0002 0002 0005 0006 0000 0004 0007 0008 0000，字段表计数器0x0002，代表当前类包含2个字段。access_flags对应0x0002，代表字段为private属性。name_index为0x0005，指向常量池第五个常量，即attribute_1。descriptor_index为0x0006，指向常量池第六个常量，即Ljava/lang/String; 。随后紧跟的0x0000代表该字段没有对应的属性。<br>字段表集合中不会列出从超类或父接口中继承而来的字段，但由可能列出原本java代码中不存在的字段，譬如在内部类中为了保持对外部类的访问性，会自动添加指向外部类实例的字段。</p>
<p>方法表与属性表集合<br>方法表集合是指由若干个方法表（method_info）组成的集合。对于在类中定义的若干个，经过JVM编译成class文件后，会将相应的method方法信息组织到一个叫做方法表集合的结构中，字段表集合是一个类数组结构，如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">struct method &#123;</span><br><span class="line">u2 method_counts;</span><br><span class="line">method_info[] method_infos;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>方法表结构method_info如下:<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">struct method_info &#123;</span><br><span class="line">u2 access_flags;</span><br><span class="line">u2 name_index;</span><br><span class="line">u2 descriptor_index;</span><br><span class="line">u2 attributes_count;</span><br><span class="line">attribute_info attributes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个结构跟field_info结构几乎完全一致，但因为volatile关键字和transient关键字不能修饰方法，所以方法表中的访问标志没有了ACC_VOLATILE标志和ACC_TRANSIENT标志。与之相对的方法表中增加了ACC_SYNCHRONIZED、ACC_NATIVE、ACC_STRICTFP、ACC_ABSTRACT。</p>
<table>
<thead>
<tr>
<th>标志名称</th>
<th>标志值</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>ACC_PUBLIC</td>
<td>0x0001</td>
<td>是否为public</td>
</tr>
<tr>
<td>ACC_PRIVATE</td>
<td>0x0002</td>
<td>是否为private</td>
</tr>
<tr>
<td>ACC_PROTECTED</td>
<td>0x0004</td>
<td>是否为protected</td>
</tr>
<tr>
<td>ACC_STATIC</td>
<td>0x0008</td>
<td>是否为static</td>
</tr>
<tr>
<td>ACC_FINAL</td>
<td>0x0010</td>
<td>是否为final</td>
</tr>
<tr>
<td>ACC_SYNCHRONIZED</td>
<td>0x0020</td>
<td>是否为synchronized</td>
</tr>
<tr>
<td>ACC_BRIDGE</td>
<td>0x0040</td>
<td>是否为编译器产生的桥接方法</td>
</tr>
<tr>
<td>ACC_VARARGS</td>
<td>0x0080</td>
<td>是否接受不定参数</td>
</tr>
<tr>
<td>ACC_NATIVE</td>
<td>0x0100</td>
<td>是否为native</td>
</tr>
<tr>
<td>ACC_ABSTRACT</td>
<td>0x0400</td>
<td>是否为abstract</td>
</tr>
<tr>
<td>ACC_STRICTFP</td>
<td>0x0800</td>
<td>是否为strictfp</td>
</tr>
<tr>
<td>ACC_SYNTHETIC</td>
<td>0x1000</td>
<td>是否为编译器自动产生</td>
</tr>
</tbody>
</table>
<p>方法的名称索引、描述索引与字段类似，方法里的代码经过编译器编译成字节码指令后，存放在方法属性表集合中。在Class文件，字段表，方法表中都可以携带自己的属性表集合，以用于描述某些场景专有的信息。与Class文件中其它的数据项目要求的顺序、长度和内容不同，属性表集合的限制稍微宽松一些，不再要求各个属性表具有严格的顺序，并且只要不与已有的属性名重复，任何人实现的编译器都可以向属性表中写入自己定义的属性信息，Java虚拟机运行时会忽略掉它不认识的属性。<br>属性表的通用结构如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">struct attribute_info &#123;</span><br><span class="line">u2 attribute_name_index;</span><br><span class="line">u4 attribute_length;</span><br><span class="line">u1 info[attribute_length];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>目前jvm常见的预定义属性包括：<br><img src="/2017/05/21/first/step6.png" alt="加载中"><br>下面详细说明下Code、LineNumberTable、LocalVariableTable属性。<br>code属性<br>Java程序方法体中的代码经过Javac编译器处理后，最终变成字节码指令存储在code属性内。Code属性表的结果如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">struct Code &#123;</span><br><span class="line">u2 attribute_name_index;</span><br><span class="line">u4 attribute_length;</span><br><span class="line">u2 max_stack;</span><br><span class="line">u2 max_locals;</span><br><span class="line">u4 code_length;</span><br><span class="line">u1 code[code_length];</span><br><span class="line">u2 exception_table_length;</span><br><span class="line">exception_info exception_table;</span><br><span class="line">u2 attribute_count;</span><br><span class="line">attribute_info attributes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>attribute_name_index是一项指向常量表的索引，常量值固定为“Code”，它代表了该属性的属性名称，attribute_length指示了属性值的长度，由于属性名称索引与属性长度一共是6个字节，所以属性值的长度固定为整个属性表的长度减去6个字节。max_stack代表了操作数栈(Operand Stacks)的最大深度。在方法执行的任意时刻，操作数栈都不会超过这个深度。虚拟机运行的时候需要根据这个值来分配栈帧(Frame)中的操作数栈深度。max_locals代表了局部变量表所需的存储空间。在这里，max_locals的单位是Slot，Slot是虚拟机为局部变量表分配内存所使用的最小单位。<br>对于byte,char,float,int,shot,boolean,reference和returnAddress等长度不超过32位的数据类型，每个局部变量占1个Slot，而double与long这两种64位的数据类型而需要2个Slot来存放。<strong> 方法参数(包括实例方法中的隐藏参数“this”)，显示异常处理器的参数(Exception Handler Parameter,即try-catch语句中catch块所定义的异常)，方法体中定义的局部变量都需要使用局部表来存放 </strong> 。<br>另外，<strong> 并不是在方法中使用了多个局部变量，就把这些局部变量所占的Slot之和作为max_locals的值，原因是局部变量表中的Slot可以重用，当代码执行超出一个局部变量的作用域时，这个局部变量所在的Slot就可以被其他局部变量所使用，编译器会根据变量的作用域来分类Slot并分配给各个变量使用，然后计算出max_locals的大小</strong> 。<br>LineNumberTable属性<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">LineNumberTable属性用于描述Java源代码行号与字节码行号(字节码偏移量)之间的对应关系。它并不是运行时必须的属性。如果选择不生成LineNumberTable属性表，对程序运行产生的最主要的影响就是在抛出异常时，堆栈中将不会显示出错的行号，并且在调试程序的时候无法按照源码来设置断点。</span><br><span class="line"></span><br><span class="line">```js</span><br><span class="line">struct LineNumberTable &#123;</span><br><span class="line">u2 attribute_name_index;</span><br><span class="line">u4 attribute_length;</span><br><span class="line">u2 line_number_table_length;</span><br><span class="line">line_number_info line_number_table;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>其中，line_number_table是一个数量为line_number_table_length，类型为line_number_info的集合，line_number_info表包括了start_pc和line_number两个u2类型的数据项，前者是字节码行号，后者是Java源码行号。<br>LocalVariableTable属性<br>LocalVariableTable属性表用于描述栈帧中局部变量表中的变量与Java源码中定义的变量之间的关系。LocalVariableTable属性表结构如下：<br><img src="/2017/05/21/first/step7.png" alt="加载中"><br>说完那么多概念，我们回到方法表字节码：<br>0003 0001 0009 000a 0001 000b 0000 002f 0001 0001 0000<br>0005 2ab7 000c b100 0000 0200 0e00 0000 0600 0100 0000 0300<br>0f00 0000 0c00 0100 0000 0500 1000 1100 0000 0100 1200 0a<br>我们从头开始说明这块字节码的意思：0x0003代表方法表中包含3个方法，接下来的0x0001 0009 000a依次代表第一个方法的访问属性public、名称索引对应<init>、描述符索引()V。<br>0x0001代表属性表中有一个属性，0x000b对应常量池中的字符串Code，代表该属性为Code类型，0x0000 002f代表下面的code属性表长度为47个字节。0x0001栈深，0x0001局部变量表大小，0x0000 0005代码长度，0x2ab7 000c b1代码区域，0x0000异常表，0x0002属性表个数，0x000e指向常量池字符串LineNumberTable，0x0000 0006属性长度6个字节，0x0001行号表长度为1，0x0000 0003代表字节码行号为0，对应的java源码行号为3。<br>0x000f指向常量池字符串LocalVariableTable，属性长度0x0000 000c为十进制数12，0x0001局部变量表长度为1，程序计数器起始值为0x0000，索引长度对应的值为0x0005，局部变量名称为0x0010即常量this，描述符索引为0x0011，对应常量Lcom/test/doc/exp/TestClassCode，slot为0。</init></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/学习/" rel="tag"># 学习</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/21/second/" rel="next" title="java 类加载器">
                <i class="fa fa-chevron-left"></i> java 类加载器
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/05/22/first/" rel="prev" title="Linux问题解决(一)">
                Linux问题解决(一) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="腊月的季节">
          <p class="site-author-name" itemprop="name">腊月的季节</p>
          <p class="site-description motion-element" itemprop="description">腊月的季节的个人博客</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">160</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">72</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              我的其他足迹
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/qq_33433029" title="CSDN博客" target="_blank">CSDN博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://github.com/youandme66" title="GitHub" target="_blank">GitHub</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/users/767025e0c4df/timeline" title="我的简书" target="_blank">我的简书</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities" title="我的知乎" target="_blank">我的知乎</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#class类文件的结构"><span class="nav-number">1.</span> <span class="nav-text">class类文件的结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#结构体"><span class="nav-number">2.</span> <span class="nav-text">结构体</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#示例"><span class="nav-number">3.</span> <span class="nav-text">示例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">腊月的季节</span>
</div>


<div class="powered-by">
   <a class="theme-link" href="http://www.jianshu.com/users/767025e0c4df/timeline">我的简书</a> 
</div>

<div class="theme-info">
  链接 -
  <a class="theme-link" href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities">
    我的知乎
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>


  



  




	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 93245, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 93245, xid: "2017/05/21/first/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/93245/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("EAvSG3QtXW1dqzq5WQ5CjH7S-gzGzoHsz", "2aiWv7vIfVY4CjKc49aPBHFX");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

</body>
</html>
